package com.sadam.ui4;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.tabs.TabLayout;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
//import com.sadam.ui4.FragmentFriendsPage.FragmentFriendsPage;
import com.sadam.ui4.FragmentHomePage.FragmentHomePage;
import com.sadam.ui4.FragmentMessagePage.FragmentMessagesPage;
import com.sadam.ui4.FragmentPlusPage.FragmentPlusPage;
import com.sadam.ui4.FragmentSelfPage.FragmentComposition.FragmentComposition;
import com.sadam.ui4.FragmentSelfPage.FragmentComposition.FragmentLikedVideos;
import com.sadam.ui4.FragmentSelfPage.FragmentPersonalVideoPlayer;
import com.sadam.ui4.FragmentSelfPage.FragmentSelfPage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Objects;

// 主 Activity，作为应用的入口，管理底部导航栏和多个 Fragment 的切换
// 实现了多个 Fragment 定义的 OnFragmentInteractionListener 接口，
// 用于接收来自不同 Fragment 的交互事件（如点击、数据传递等）
public class MainActivity extends AppCompatActivity implements FragmentHomePage.OnFragmentInteractionListener,  FragmentPlusPage.OnFragmentInteractionListener, FragmentSelfPage.OnFragmentInteractionListener, FragmentMessagesPage.OnFragmentInteractionListener {
//    public static final String DEFAULT_SHARED_PREFERENCES = "private static final String DEFAULT_SHARED_PREFERENCES_ON_MAIN_ACTIVITY";
//    // 请求权限的请求码，用于区分不同权限的回调
//    private static final int CAMERA_PREMISSION_REQUEST_CODE = 1;
//    private static final int RECORD_AUDIO_PREMISSION_REQUEST_CODE = 2;
//    private static final int WRITE_EXTERNAL_STORAGE_PREMISSION_REQUEST_CODE = 3;
    // 底部导航栏控件
    private TabLayout tabLayoutBottom = null;
    // 当前显示的 Fragment 和各个页面的 Fragment 实例
    private Fragment currentFragment, homePageFragment, plusPageFragment, messagesPageFragment, selfPageFragment;
    // 当前登录用户对象
    private User currentUser;
    // 数据库帮助类实例，用于操作 SQLite 数据库
    private MySqLiteOpenHelper mySqLiteOpenHelper;

    private FragmentMessagesPage messagesFragment;

    // 权限请求配置数组：每项包含权限字符串和对应的中文描述
    // 用于统一管理权限请求与提示信息
//    private String[][] PERMISSIONS_REQUESTED = new String[][]{
//            new String[]{Manifest.permission.CAMERA, "相机"},
//            new String[]{Manifest.permission.RECORD_AUDIO, "音频录制"},
////            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, "外置文件写入"}
//
//    };

    /**
     * 自定义 Fragment 替换方法
     * 作用：在指定容器中显示目标 Fragment，隐藏当前 Fragment
     * 实现"单 Activity 多 Fragment"页面切换效果，避免重复创建 Fragment
     * @param appCompatActivity 当前 Activity
     * @param containerLayout_id 容器布局 ID（如 R.id.frameLayout1）
     * @param currentFragment 当前正在显示的 Fragment
     * @param targetFragment 要切换到的目标 Fragment
     * @return 返回目标 Fragment
     */
    public static Fragment SadamReplaceFragment(FragmentActivity appCompatActivity, int containerLayout_id, Fragment currentFragment, Fragment targetFragment) {
        FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (!targetFragment.isAdded()) {
            // 如果目标 Fragment 还未添加，则先隐藏当前 Fragment，再添加目标 Fragment
            if (!(currentFragment == null)) {
                transaction.hide(currentFragment);
            }
            transaction.add(containerLayout_id, targetFragment);
        } else {
            // 如果目标 Fragment 已添加，则隐藏当前 Fragment，显示目标 Fragment
            transaction.hide(currentFragment);
            transaction.show(targetFragment);
        }
        transaction.commit();
        // 打印当前切换到的 Fragment 类名，用于调试
        Log.e("xxx:", targetFragment.getClass().getName());
        return targetFragment;
    }
    /**
     * 权限请求结果回调方法
     * 当用户对权限请求做出响应后，系统会调用此方法
     * 根据 requestCode 判断是哪个权限的请求，并给出相应提示
     */
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
////        for (int i = 0; i < permissions.length; i++) {
////            if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
////                for (String[] permissionPair : PERMISSIONS_REQUESTED) {
////                    if (permissionPair[0].equals(permissions[i])) {
////                        Toast.makeText(getApplicationContext(), permissionPair[1] + "权限申请成功", Toast.LENGTH_SHORT).show();
////                        break;
////                    }
////                }
////            } else {
////                Toast.makeText(getApplicationContext(), "申请" + permissions[i] + "权限失败！", Toast.LENGTH_SHORT).show();
////            }
////        }
//    }
    /**
     * Activity 创建时调用
     * 初始化数据库、用户信息、Fragment、底部导航栏，并请求必要权限
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化数据库帮助类
//        mySqLiteOpenHelper = new MySqLiteOpenHelper(MainActivity.this, MySqLiteOpenHelper.DATABASE_NAME, null, MySqLiteOpenHelper.DATABASE_VERSION);
        try {
            // 初始化数据库帮助类
            mySqLiteOpenHelper = new MySqLiteOpenHelper(MainActivity.this, MySqLiteOpenHelper.DATABASE_NAME, null, MySqLiteOpenHelper.DATABASE_VERSION);
        } catch (Exception e) {
            Log.e("Database", "数据库初始化失败", e);
            Toast.makeText(this, "数据库初始化失败", Toast.LENGTH_SHORT).show();
            return;
        }
        // 从 SharedPreferences 中读取当前登录用户信息，并从数据库加载完整用户数据
        // 从 SharedPreferences 中读取当前登录用户信息
        currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(MainActivity.this, mySqLiteOpenHelper);

// 添加空值检查
        if (currentUser == null) {
            Log.e("MainActivity", "用户未登录或获取用户信息失败");
            // 跳转到登录页面
            Intent intent = new Intent(this, ActivityLogin.class);
            startActivity(intent);
            finish();
            return;
        }
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "test.txt");
        try {
            FileOutputStream fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 设置界面布局文件
        setContentView(R.layout.activity_main);
        // 创建各个页面的 Fragment 实例
// 创建各个页面的 Fragment 实例
        try {
            homePageFragment = new FragmentHomePage();
//            friendsPageFragment = new FragmentFriendsPage();
            plusPageFragment = new FragmentPlusPage();
            messagesPageFragment = new FragmentMessagesPage();
            selfPageFragment = new FragmentSelfPage();
        } catch (Exception e) {
            Log.e("Fragment", "Fragment初始化失败", e);
            Toast.makeText(this, "页面初始化失败", Toast.LENGTH_SHORT).show();
            return;
        }
        // 绑定底部 TabLayout 控件
        tabLayoutBottom = findViewById(R.id.tabLayoutBottom);
        tabLayoutBottom.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // ✅ 新增：切换 Tab 前，弹出所有回退栈中的 Fragment
                popAllBackStack();

                switch (tab.getPosition()) {
                    case 0:
                        currentFragment = SadamReplaceFragment(MainActivity.this, R.id.frameLayout1, currentFragment, homePageFragment);
                        break;
//                    case 1:
//                        currentFragment = SadamReplaceFragment(MainActivity.this, R.id.frameLayout1, currentFragment, friendsPageFragment);
//                        break;
                    case 1:
                        currentFragment = SadamReplaceFragment(MainActivity.this, R.id.frameLayout1, currentFragment, plusPageFragment);
                        break;
                    case 2:
                        currentFragment = SadamReplaceFragment(MainActivity.this, R.id.frameLayout1, currentFragment, messagesPageFragment);
                        break;
                    case 3:
                        currentFragment = SadamReplaceFragment(MainActivity.this, R.id.frameLayout1, currentFragment, selfPageFragment);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
        Objects.requireNonNull(tabLayoutBottom.getTabAt(1)).select();
        Objects.requireNonNull(tabLayoutBottom.getTabAt(0)).select();
        // 检查并请求应用所需权限
//        checkPermissions();
    }
    /**
     * 弹出所有回退栈中的 Fragment，直到栈为空
     */
    private void popAllBackStack() {
        FragmentManager fm = getSupportFragmentManager();
        Log.d("MainActivity", "📌 开始清理回退栈，当前大小: " + fm.getBackStackEntryCount());

        // 循环弹出
        while (fm.getBackStackEntryCount() > 0) {
            try {
                fm.popBackStackImmediate(); // 立即弹出
                Log.d("MainActivity", " popped one entry");
            } catch (Exception e) {
                Log.e("MainActivity", "弹出回退栈失败", e);
            }
        }

        Log.d("MainActivity", "✅ 回退栈已清空");
    }

    public void switchToHomePage() {
        runOnUiThread(() -> {
            popAllBackStack(); // ✅ 保险起见，先清理
            Objects.requireNonNull(tabLayoutBottom.getTabAt(0)).select();
            currentFragment = SadamReplaceFragment(this, R.id.frameLayout1, currentFragment, homePageFragment);

            if (homePageFragment instanceof FragmentHomePage) {
                ((FragmentHomePage) homePageFragment).refresh();
            }
        });
    }

    /**
     * ✅ 增强版：刷新主页和其他相关页面
     */
    public void refreshHomePage() {
        // 刷新主页
        refreshHomePageInternal();

        // 刷新个人视频播放器（如果存在）
        refreshPersonalVideoPlayerSafe();
    }

    /**
     * ✅ 安全刷新主页
     */
    private void refreshHomePageInternal() {
        try {
            if (homePageFragment instanceof FragmentHomePage) {
                ((FragmentHomePage) homePageFragment).refresh();
                Log.d("MainActivity", "主页刷新完成");
            }
        } catch (Exception e) {
            Log.e("MainActivity", "刷新主页失败", e);
        }
    }

    /**
     * ✅ 安全刷新个人视频播放器
     */
    private void refreshPersonalVideoPlayerSafe() {
        try {
            FragmentPersonalVideoPlayer player = findPersonalVideoPlayerSafe();
            if (isFragmentValid(player)) {
                player.refreshVideoData();
                Log.d("MainActivity", "个人视频播放器刷新完成");
            }
        } catch (Exception e) {
            Log.e("MainActivity", "刷新个人视频播放器失败", e);
        }
    }

    /**
     * ✅ 安全查找个人视频播放器
     */
    private FragmentPersonalVideoPlayer findPersonalVideoPlayerSafe() {
        if (getSupportFragmentManager().isDestroyed()) {
            return null;
        }

        try {
            Fragment fragment = getSupportFragmentManager()
                    .findFragmentByTag(FragmentPersonalVideoPlayer.class.getName());

            return (fragment instanceof FragmentPersonalVideoPlayer) ?
                    (FragmentPersonalVideoPlayer) fragment : null;
        } catch (Exception e) {
            Log.e("MainActivity", "查找个人视频播放器异常", e);
            return null;
        }
    }

    /**
     * ✅ 检查Fragment是否有效
     */
    private boolean isFragmentValid(Fragment fragment) {
        return fragment != null &&
                fragment.isAdded() &&
                !fragment.isRemoving() &&
                !fragment.getActivity().isFinishing();
    }

    /**
     * ✅ 新增：刷新消息页面和我的页面（作品和点赞视频）
     * 在评论成功后调用，确保相关页面数据同步更新
     */
    public void refreshMessageAndSelfPages() {
        Log.d("MainActivity", "开始刷新消息页面和我的页面");

        // 刷新消息页面（如果存在且可见）
        FragmentMessagesPage messagesPage = findFragmentMessagesPage();
        if (messagesPage != null && messagesPage.isVisible()) {
            messagesPage.refreshMessages();
            Log.d("MainActivity", "已刷新消息页面");
        }

        // 刷新个人页面相关的作品和点赞视频
        FragmentSelfPage selfPage = findFragmentSelfPage();
        if (selfPage != null && selfPage.isVisible()) {
            // 如果个人页面可见，刷新其内部的作品和点赞视频
            selfPage.refreshCompositionAndLikedVideos();
            Log.d("MainActivity", "已刷新个人页面相关内容");
        }

        // 备用方案：直接查找作品和点赞视频的Fragment
        refreshCompositionDirectly();
        refreshLikedVideosDirectly();
    }

    /**
     * 查找消息页面Fragment
     */
    private FragmentMessagesPage findFragmentMessagesPage() {
        // 先检查当前显示的Fragment
        if (currentFragment instanceof FragmentMessagesPage) {
            return (FragmentMessagesPage) currentFragment;
        }

        // 通过类名查找
        return (FragmentMessagesPage) getSupportFragmentManager()
                .findFragmentByTag(FragmentMessagesPage.class.getName());
    }

    /**
     * 查找个人页面Fragment
     */
    private FragmentSelfPage findFragmentSelfPage() {
        // 先检查当前显示的Fragment
        if (currentFragment instanceof FragmentSelfPage) {
            return (FragmentSelfPage) currentFragment;
        }

        // 通过类名查找
        return (FragmentSelfPage) getSupportFragmentManager()
                .findFragmentByTag(FragmentSelfPage.class.getName());
    }

    /**
     * 直接刷新作品页面（备用方案）
     */
    private void refreshCompositionDirectly() {
        try {
            // 通过类名查找作品Fragment
            FragmentComposition composition = (FragmentComposition) getSupportFragmentManager()
                    .findFragmentByTag(FragmentComposition.class.getName());
            if (composition != null && composition.isVisible()) {
                composition.loadUserVideos();
                Log.d("MainActivity", "直接刷新作品页面");
            }
        } catch (Exception e) {
            Log.e("MainActivity", "刷新作品页面失败", e);
        }
    }

    /**
     * 直接刷新点赞视频页面（备用方案）
     */
    private void refreshLikedVideosDirectly() {
        try {
            // 通过类名查找点赞视频Fragment
            FragmentLikedVideos likedVideos = (FragmentLikedVideos) getSupportFragmentManager()
                    .findFragmentByTag(FragmentLikedVideos.class.getName());
            if (likedVideos != null && likedVideos.isVisible()) {
                likedVideos.refresh();
                Log.d("MainActivity", "直接刷新点赞视频页面");
            }
        } catch (Exception e) {
            Log.e("MainActivity", "刷新点赞视频页面失败", e);
        }
    }


    /**
     * ✅ 新增：暂停首页视频
     */
    public void pauseHomePageVideos() {
        if (homePageFragment instanceof FragmentHomePage) {
            ((FragmentHomePage) homePageFragment).pauseAllVideos();
        }
    }

    /**
     * ✅ 新增：恢复首页视频（仅第一个可见的）
     */
    public void resumeHomePageVideos() {
        if (homePageFragment instanceof FragmentHomePage) {
            ((FragmentHomePage) homePageFragment).resumeVideoIfVisible();
        }
    }
    /**
     * 检查并请求运行时权限
     * 遍历权限数组，对未授权的权限发起请求
     */
//    private void checkPermissions() {
//        for (int i = 0; i < PERMISSIONS_REQUESTED.length; i++) {
//            if (checkSelfPermission(PERMISSIONS_REQUESTED[i][0]) == PackageManager.PERMISSION_GRANTED) {
//                Toast.makeText(getApplicationContext(), "已经获取" + PERMISSIONS_REQUESTED[i][1] + "权限", Toast.LENGTH_SHORT).show();
//            } else {
//                requestPermissions(new String[]{PERMISSIONS_REQUESTED[i][0]}, i);
//            }
//        }
//    }
    /**
     * 提供对数据库帮助类的访问
     * 供其他组件（如 Fragment）调用数据库操作
     * @return 返回 mySqLiteOpenHelper 实例
     */
    public MySqLiteOpenHelper getMySqLiteOpenHelper() {
        return mySqLiteOpenHelper;
    }
    /**
     * 实现 Fragment 交互接口方法
     * 当 Fragment 触发 onFragmentInteraction 时回调此方法
     * 当前仅打印传递的 Uri 信息，可用于进一步处理（如跳转、数据加载）
     */

    @Override
    public void onFragmentInteraction(Uri uri) {
        Log.e("xx:", uri.toString());
    }

    public void refreshFragmentComposition() {
        // 尝试通过标签获取 FragmentComposition
        FragmentComposition fragmentComposition = (FragmentComposition) getSupportFragmentManager().findFragmentByTag("fragmentComposition");

        // 如果找不到，尝试通过类名查找
        if (fragmentComposition == null) {
            fragmentComposition = (FragmentComposition) getSupportFragmentManager().findFragmentByTag(FragmentComposition.class.getName());
        }

        if (fragmentComposition != null) {
            fragmentComposition.loadUserVideos();
        }
    }
}